
#include "lmexxx_conf.h"

#define MATCHING_ACK_BUFF_SIZE			16
#define WAIT_TIME_TICK_MS				100

typedef struct{
	uint8_t* msg;
	uint16_t msg_len;
	uint16_t matching_time_tick;
}MATCHING_ACK_ITEM_STRUCT;

static MATCHING_ACK_ITEM_STRUCT matching_ack_buff[MATCHING_ACK_BUFF_SIZE];
static uint8_t matching_ack_timer = 0xff;

extern void matching_ack_timeout_hook(uint8_t* match_msg, uint16_t msg_len);
extern uint8_t matching_ack_rec_hook(uint8_t* rec_msg, uint16_t rec_msg_len, 
								uint8_t* match_msg, uint16_t match_msg_len);

uint8_t matching_ack_rec(uint8_t* rec_msg, uint16_t rec_msg_len)
{
	for(uint8_t i = 0; i < MATCHING_ACK_BUFF_SIZE; i++){
		if(matching_ack_buff[i].matching_time_tick > 0){
			if(matching_ack_rec_hook(rec_msg, rec_msg_len,
					matching_ack_buff[i].msg, matching_ack_buff[i].msg_len)){	//macth ok
				matching_ack_buff[i].matching_time_tick = 0;
				return 1;
			}
		}
	}
	return 0;
}

uint8_t matching_ack_match(uint8_t* msg, uint16_t msg_len, uint16_t matching_time_tick)
{
	if(matching_time_tick == 0)
	{
		return 0;
	}
	for(uint8_t i = 0; i < MATCHING_ACK_BUFF_SIZE; i++){
		if(0 == matching_ack_buff[i].matching_time_tick){
			matching_ack_buff[i].msg = msg;
			matching_ack_buff[i].msg_len = msg_len;
			matching_ack_buff[i].matching_time_tick = matching_time_tick;
			if(0 == APP_CheckGenTimerRunning(matching_ack_timer)){
				APP_StartGenTimer(matching_ack_timer);
			}
			return 1;
		}
	}
	return 0;
}

static void matching_ack_timer_handler(void)
{
	uint8_t empty = 1;
	for(uint8_t i = 0; i < MATCHING_ACK_BUFF_SIZE; i++){
		if(matching_ack_buff[i].matching_time_tick > 0){
			empty = 0;
			matching_ack_buff[i].matching_time_tick--;
			if(matching_ack_buff[i].matching_time_tick == 0){
				matching_ack_timeout_hook(matching_ack_buff[i].msg, matching_ack_buff[i].msg_len);
			}
		}
	}
	if(empty){
		APP_StopGenTimer(matching_ack_timer);
	}
}

uint8_t matching_ack_init(void)
{
	if(matching_ack_timer == 0xff){
		matching_ack_timer = APP_NewGenTimer(WAIT_TIME_TICK_MS, matching_ack_timer_handler);
		if(matching_ack_timer == 0xff){
			return 0;
		}
	}

	for(uint8_t i = 0; i < MATCHING_ACK_BUFF_SIZE; i++){
		matching_ack_buff[i].matching_time_tick = 0;
	}
	return 1;
}
